package com.fxsh168.server.maps;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.navisdk.adapter.BNRouteGuideManager;
import com.baidu.navisdk.adapter.BNRouteGuideManager.CustomizedLayerItem;
import com.baidu.navisdk.adapter.BNRouteGuideManager.OnNavigationListener;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNRoutePlanNode.CoordinateType;
import com.baidu.navisdk.adapter.BNaviBaseCallbackModel;
import com.baidu.navisdk.adapter.BaiduNaviCommonModule;
import com.baidu.navisdk.adapter.NaviModuleFactory;
import com.baidu.navisdk.adapter.NaviModuleImpl;
import com.baidu.trace.OnEntityListener;
import com.baidu.trace.OnStartTraceListener;
import com.baidu.trace.OnStopTraceListener;
import com.baidu.trace.OnTrackListener;
import com.baidu.trace.TraceLocation;
import com.fxsh168.server.R;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.maps.yinyan.DateUtils;
import com.fxsh168.server.maps.yinyan.MonitorService;
import com.fxsh168.server.maps.yinyan.TrackReceiver;
import com.fxsh168.server.otherviews.banner.MyApplication;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import java.util.List;


public class BNDemoGuideActivity extends Activity {
    private BNRoutePlanNode mBNRoutePlanNode = null;
    private BaiduNaviCommonModule mBaiduNaviCommonModule = null;
    String ids, actionSend;      //订单id，距离，导航标识
    /*
     * 对于导航模块有两种方式来实现发起导航。 1：使用通用接口来实现 2：使用传统接口来实现
     */
    // 是否使用通用接口
    private boolean useCommonInterface = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NavQian.activityList.add(this);
        createHandler();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        }
        View view = null;
        if (useCommonInterface) {
            //使用通用接口
            mBaiduNaviCommonModule = NaviModuleFactory.getNaviModuleManager().getNaviCommonModule(
                    NaviModuleImpl.BNaviCommonModuleConstants.ROUTE_GUIDE_MODULE, this,
                    BNaviBaseCallbackModel.BNaviBaseCallbackConstants.CALLBACK_ROUTEGUIDE_TYPE, mOnNavigationListener);
            if (mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onCreate();
                view = mBaiduNaviCommonModule.getView();
            }

        } else {
            //使用传统接口
            view = BNRouteGuideManager.getInstance().onCreate(this, mOnNavigationListener);
        }
        //初始化视图
        if (view != null) {
            setContentView(view);
        }
        //获取页面跳转传递过来的信息
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            mBNRoutePlanNode = (BNRoutePlanNode) bundle.getSerializable(NavQian.ROUTE_PLAN_NODE);
            ids = intent.getStringExtra("cid");
            actionSend = intent.getAction();
            Log.e("tag", "接收到的数据" + ids + "标识" + actionSend);
        }
        //显示自定义图标
        if (hd != null) {
            hd.sendEmptyMessageAtTime(MSG_SHOW, 5000);
        }
        //如果是乘客已经上车的，就初始化鹰眼服务
        if (actionSend.equals("btnRouteSchedul")) {
//            aboutYing();
        }
    }

    //   关于鹰眼服务的全部初始化
    public void aboutYing() {
        //       关于鹰眼服务的---------------------------------------------------
        init();           // 初始化
        initListener();     // 初始化监听器
        setInterval();      // 设置采集周期
        setRequestType();    // 设置http请求协议类型
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (useCommonInterface) {
            if (mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onResume();
            }
        } else {
            BNRouteGuideManager.getInstance().onResume();
        }
    }


    @Override
    public void onBackPressed() {
        if (useCommonInterface) {
            if (mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onBackPressed(false);
            }
        } else {
            BNRouteGuideManager.getInstance().onBackPressed(false);
        }
    }

    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (useCommonInterface) {
            if (mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onConfigurationChanged(newConfig);
            }
        } else {
            BNRouteGuideManager.getInstance().onConfigurationChanged(newConfig);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if (useCommonInterface) {
            if (mBaiduNaviCommonModule != null) {
                Bundle mBundle = new Bundle();
                mBundle.putInt(RouteGuideModuleConstants.KEY_TYPE_KEYCODE, keyCode);
                mBundle.putParcelable(RouteGuideModuleConstants.KEY_TYPE_EVENT, event);
                mBaiduNaviCommonModule.setModuleParams(RouteGuideModuleConstants.METHOD_TYPE_ON_KEY_DOWN, mBundle);
                try {
                    Boolean ret = (Boolean) mBundle.get(RET_COMMON_MODULE);
                    if (ret) {
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    private void addCustomizedLayerItems() {
        List<CustomizedLayerItem> items = new ArrayList<CustomizedLayerItem>();
        CustomizedLayerItem item1 = null;
        if (mBNRoutePlanNode != null) {
            item1 = new CustomizedLayerItem(mBNRoutePlanNode.getLongitude(), mBNRoutePlanNode.getLatitude(),
                    mBNRoutePlanNode.getCoordinateType(), getResources().getDrawable(R.mipmap.ditu),
                    CustomizedLayerItem.ALIGN_CENTER);
            items.add(item1);
            BNRouteGuideManager.getInstance().setCustomizedLayerItems(items);
        }
        BNRouteGuideManager.getInstance().showCustomizedLayer(true);
    }

    private static final int MSG_SHOW = 1;
    private static final int MSG_HIDE = 2;
    private static final int MSG_RESET_NODE = 3;
    private Handler hd = null;

    private void createHandler() {
        if (hd == null) {
            hd = new Handler(getMainLooper()) {
                public void handleMessage(android.os.Message msg) {
                    if (msg.what == MSG_SHOW) {
                        addCustomizedLayerItems();
                    } else if (msg.what == MSG_HIDE) {
                        BNRouteGuideManager.getInstance().showCustomizedLayer(false);
                    } else if (msg.what == MSG_RESET_NODE) {
                        BNRouteGuideManager.getInstance().resetEndNodeInNavi(
                                new BNRoutePlanNode(116.21142, 40.85087, "百度大厦11", null, CoordinateType.GCJ02));
                    }
                }
            };
        }
    }

    private OnNavigationListener mOnNavigationListener = new OnNavigationListener() {

        @Override
        public void onNaviGuideEnd() {
            //退出导航
            Intent intent = new Intent(BNDemoGuideActivity.this, NavQian.class);
            setResult(66, intent); //intent为A传来的带有Bundle的intent，当然也可以自己定义新的Bundle
            finish();
        }

        @Override
        public void notifyOtherAction(int actionType, int arg1, int arg2, Object obj) {
            if (actionType == 0) {
                //导航到达目的地 自动退出
                Intent intent = new Intent(BNDemoGuideActivity.this, NavQian.class);

                setResult(66, intent); //intent为A传来的带有Bundle的intent，当然也可以自己定义新的Bundle
                finish();//此处一定要调用finish()方法

            }
        }
    };

    private final static String RET_COMMON_MODULE = "module.ret";

    private interface RouteGuideModuleConstants {
        final static int METHOD_TYPE_ON_KEY_DOWN = 0x01;
        final static String KEY_TYPE_KEYCODE = "keyCode";
        final static String KEY_TYPE_EVENT = "event";
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (useCommonInterface) {
            if (mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onStart();
            }
        } else {
            BNRouteGuideManager.getInstance().onStart();
        }
    }

    protected void onPause() {
        super.onPause();
        if (useCommonInterface) {
            if (mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onPause();
            }
        } else {
            BNRouteGuideManager.getInstance().onPause();
        }
        isInUploadFragment = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (useCommonInterface) {
            if (mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onStop();
            }
        } else {
            BNRouteGuideManager.getInstance().onStop();
        }
////         鹰眼服务
//        stopTrace();
        if (isRegister) {
            try {
                trackApp.unregisterReceiver(trackReceiver);
                isRegister = false;
            } catch (Exception e) {
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        trackApp.getClient().onDestroy();
//         ------------------------------
        if (useCommonInterface) {
            if (mBaiduNaviCommonModule != null) {
                mBaiduNaviCommonModule.onDestroy();
            }
        } else {
            BNRouteGuideManager.getInstance().onDestroy();
        }
        NavQian.activityList.remove(this);
    }


    //    ----------------------------------鹰眼轨迹----------------------------------
    private MyApplication trackApp = null;
    protected static OnStartTraceListener startTraceListener = null; //   * 开启轨迹服务监听器
    protected static OnStopTraceListener stopTraceListener = null;   //     * 停止轨迹服务监听器
    //    private TrackUploadHandler mHandler = null;
    boolean isTraceStarted = false;
    protected RefreshThread refreshThread = null;      //  * 刷新地图线程(获取实时点)
    private int packInterval = 15;   // * 打包周期（单位 : 秒）
    private static OnEntityListener entityListener = null;      //  * Entity监听器
    private int gatherInterval = 5;  //     * 采集周期（单位 : 秒）
    private static List<LatLng> pointList = new ArrayList<LatLng>();
    protected static boolean isInUploadFragment = true;
    private static Overlay overlay = null;
    protected static MapStatusUpdate msUpdate = null;
    private static BitmapDescriptor realtimeBitmap;         //   * 图标
    protected static OverlayOptions overlayOptions;        // 覆盖物
    private static PolylineOptions polyline = null;        // 路线覆盖物
    private Intent serviceIntent = null;
    private static boolean isRegister = false;
    protected static PowerManager pm = null;
    private TrackReceiver trackReceiver = new TrackReceiver();
    public static PowerManager.WakeLock wakeLock = null;

    public void init() {
        Toast.makeText(this, "正在开启轨迹服务，请稍候", Toast.LENGTH_SHORT).show();
        startTrace();
        if (!isRegister) {
            if (null == pm) {
                pm = (PowerManager) trackApp.getSystemService(Context.POWER_SERVICE);
            }
            if (null == wakeLock) {
                wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track upload");
            }
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction("com.baidu.trace.action.GPS_STATUS");
            trackApp.registerReceiver(trackReceiver, filter);
            isRegister = true;
        }
    }

    //    * 设置采集周期和打包周期
    private void setInterval() {
        trackApp.getClient().setInterval(gatherInterval, packInterval);
    }

    /**
     * 设置请求协议
     */
    protected void setRequestType() {
        int type = 0;
        trackApp.getClient().setProtocolType(type);
    }

//     * 初始化监听器

    private void initListener() {
        // 初始化开启轨迹服务监听器
        if (null == startTraceListener) {
            initOnStartTraceListener();
        }

        // 初始化停止轨迹服务监听器
        if (null == stopTraceListener) {
            initOnStopTraceListener();
        }

        // 初始化entity监听器
        if (null == entityListener) {
            initOnEntityListener();
        }
    }

    /**
     * 初始化OnEntityListener
     */
    private void initOnEntityListener() {
        entityListener = new OnEntityListener() {
            // 请求失败回调接口
            @Override
            public void onRequestFailedCallback(String arg0) {
//                trackApp.getmHandler().obtainMessage(0, "entity请求失败回调接口消息 : " + arg0).sendToTarget();
            }

            // 添加entity回调接口
            public void onAddEntityCallback(String arg0) {
//                trackApp.getmHandler().obtainMessage(0, "添加entity回调接口消息 : " + arg0).sendToTarget();
            }

            // 查询entity列表回调接口
            @Override
            public void onQueryEntityListCallback(String message) {
                TraceLocation entityLocation = new TraceLocation();
                try {
                    JSONObject dataJson = new JSONObject(message);
                    if (dataJson.has("status") && dataJson.getInt("status") == 0
                            && dataJson.has("size") && dataJson.getInt("size") > 0) {
                        JSONArray entities = dataJson.getJSONArray("entities");
                        JSONObject entity = entities.getJSONObject(0);
                        JSONObject point = entity.getJSONObject("realtime_point");
                        JSONArray location = point.getJSONArray("location");
                        entityLocation.setLongitude(location.getDouble(0));
                        entityLocation.setLatitude(location.getDouble(1));
                    }
                } catch (JSONException e) {
//                    trackApp.getmHandler().obtainMessage(0, "解析entityList回调消息失败").sendToTarget();
                    return;
                }

            }

            @Override
            public void onReceiveLocation(TraceLocation location) {

            }

        };
    }





    /**
     * 初始化OnStartTraceListener
     */
    private void initOnStartTraceListener() {
        // 初始化startTraceListener
        startTraceListener = new OnStartTraceListener() {
            // 开启轨迹服务回调接口（arg0 : 消息编码，arg1 : 消息内容，详情查看类参考）
            public void onTraceCallback(int arg0, String arg1) {
//                mHandler.obtainMessage(arg0, "开启轨迹服务回调接口消息 [消息编码 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
            }

            // 轨迹服务推送接口（用于接收服务端推送消息，arg0 : 消息类型，arg1 : 消息内容，详情查看类参考）
            public void onTracePushCallback(byte arg0, String arg1) {
                if (0x03 == arg0 || 0x04 == arg0) {
                    try {
                        JSONObject dataJson = new JSONObject(arg1);
                        if (null != dataJson) {
                            String mPerson = dataJson.getString("monitored_person");
                            String action = dataJson.getInt("action") == 1 ? "进入" : "离开";
                            String date = DateUtils.getDate(dataJson.getInt("time"));
                            long fenceId = dataJson.getLong("fence_id");
//                            mHandler.obtainMessage(-1, "监控对象[" + mPerson + "]于" + date + " [" + action + "][" + fenceId + "号]围栏").sendToTarget();
                        }

                    } catch (JSONException e) {
//                        mHandler.obtainMessage(-1, "轨迹服务推送接口消息 [消息类型 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                    }
                } else {
//                    mHandler.obtainMessage(-1, "轨迹服务推送接口消息 [消息类型 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                }
            }

        };
    }


    /**
     * 初始化OnStopTraceListener
     */
    private void initOnStopTraceListener() {
        // 初始化stopTraceListener
        stopTraceListener = new OnStopTraceListener() {
            // 轨迹服务停止成功
            public void onStopTraceSuccess() {
//                mHandler.obtainMessage(1, "停止轨迹服务成功").sendToTarget();
                startRefreshThread(false);
                trackApp.getClient().onDestroy();
            }

            // 轨迹服务停止失败（arg0 : 错误编码，arg1 : 消息内容，详情查看类参考）
            public void onStopTraceFailed(int arg0, String arg1) {
//                mHandler.obtainMessage(-1, "停止轨迹服务接口消息 [错误编码 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                startRefreshThread(false);
            }
        };
    }

    protected void startRefreshThread(boolean isStart) {
        if (null == refreshThread) {
            refreshThread = new RefreshThread();
        }
        refreshThread.refresh = isStart;
        if (isStart) {
            if (!refreshThread.isAlive()) {
                refreshThread.start();
            }
        } else {
            refreshThread = null;
        }
    }


    protected class RefreshThread extends Thread {
        protected boolean refresh = true;

        @Override
        public void run() {
            Looper.prepare();
            while (refresh) {
                // 轨迹服务开启成功后，调用queryEntityList()查询最新轨迹；
                // 未开启轨迹服务时，调用queryRealtimeLoc()进行实时定位。
                if (isTraceStarted) {
//                    queryEntityList();
                } else {
//                    aboutYing();
                    queryRealtimeLoc();
                }
                try {
                    Thread.sleep(gatherInterval * 1000);
                } catch (InterruptedException e) {
                    System.out.println("线程休眠失败");
                }
            }
            Looper.loop();
        }
    }


    /**
     * 查询实时轨迹
     */
    private void queryRealtimeLoc() {
        trackApp.getClient().queryRealtimeLoc(trackApp.getServiceId(), entityListener);
    }


    /**
     * 开启轨迹服务
     */
    private void startTrace() {
        trackApp = (MyApplication) getApplicationContext();
        // 通过轨迹服务客户端client开启轨迹服务
        trackApp.getClient().startTrace(trackApp.getTrace(), startTraceListener);
        if (!MonitorService.isRunning) {
            // 开启监听service
            MonitorService.isCheck = true;
            MonitorService.isRunning = true;
            startMonitorService();
        }
    }

    /**
     * 停止轨迹服务
     */
    private void stopTrace() {
        // 停止监听service
        MonitorService.isCheck = false;
        MonitorService.isRunning = false;
        // 通过轨迹服务客户端client停止轨迹服务
        trackApp.getClient().stopTrace(trackApp.getTrace(), stopTraceListener);
        if (null != serviceIntent) {
            trackApp.stopService(serviceIntent);
        }
    }

    public void startMonitorService() {
        serviceIntent = new Intent(trackApp, MonitorService.class);
        trackApp.startService(serviceIntent);
    }

}
